using System.Runtime;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using MyTools;
public class OutsiderPointer : MonoBehaviour
{

    [Header("代码中设置")]
    public GameObject go_PointerTo;
    public GameObject go_PointerFrom;
    [Header("手动设置")]
    public GameObject go_Shower;
    private bool bIsShow = true;
    void Update()
    {
        if (bIsShow && go_PointerTo != null && go_PointerFrom != null){
            Vector2 v2PointedOnScreen = Camera.main.WorldToScreenPoint(go_PointerTo.transform.position);
            Vector2 v2PointedFromOnScreen = Camera.main.WorldToScreenPoint(go_PointerFrom.transform.position);
            
            Vector2 v2LeftBottom = Camera.main.ViewportToScreenPoint(new Vector2(0, 0));
            Vector2 v2RightTop = Camera.main.ViewportToScreenPoint(new Vector2(1, 1));
            Vector2 v2RightBottom = new Vector2(v2RightTop.x, v2LeftBottom.y);
            Vector2 v2LeftTop = new Vector2(v2LeftBottom.x, v2RightTop.y);

            Vector2[] rectCorners = { v2LeftBottom, v2RightBottom, v2RightTop, v2LeftTop };
            bool bHasCross = false;
            for (int i = 0; i < rectCorners.Length; i++)
            {
                Vector2 intersection;
                if (MyMath.LineSegmentIntersection(v2PointedFromOnScreen, v2PointedOnScreen, rectCorners[i], rectCorners[(i + 1) % rectCorners.Length], out intersection))
                {
                    transform.position = intersection;
                    bHasCross=true;
                    break;
                }
            }
            if(!bHasCross){
                transform.position = v2PointedOnScreen;
            }

            transform.rotation = Quaternion.Euler(0, 0, MyMath.GetGlobalFaceAngle2D(go_PointerFrom.transform.position - go_PointerTo.transform.position));
        }
        if (go_PointerFrom==null || go_PointerTo==null){
            OutsiderPointerPool.listOfGo_OutsiderPointer.Remove(gameObject);
            Destroy(gameObject);
        }
        if(CheckNeedShow()){
            Show(true);
        }else{
            Show(false);
        }
    }

    public void Show(bool bShow){
        bIsShow = bShow;
        go_Shower.SetActive(bShow);
    }
    private bool CheckNeedShow(){
        if (go_PointerFrom == null || go_PointerTo == null){return false;}
        Vector2 v2PointedOnScreeen = Camera.main.WorldToScreenPoint(go_PointerTo.transform.position);
        Vector2 v2LeftBottom = Camera.main.ViewportToScreenPoint(new Vector2(0, 0));
        Vector2 v2RightTop = Camera.main.ViewportToScreenPoint(new Vector2(1, 1));
        if (v2PointedOnScreeen.x < v2LeftBottom.x || v2PointedOnScreeen.x > v2RightTop.x || v2PointedOnScreeen.y < v2LeftBottom.y || v2PointedOnScreeen.y > v2RightTop.y){return true;}
        else{return false;}
    }
}
